package com.up4years.utils;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
public class ParamUtils {
	public static int param2Int(String value, int defaultValue) {
		if (StringUtils.isNotBlank(value)) {
			return Integer.parseInt(value);
		}
		return defaultValue;
	}
	public static String encodeString(String value) {
		String parmValue = parm2String(value, "");
		try {
			parmValue = URLEncoder.encode(parmValue, "utf-8");
		} catch (UnsupportedEncodingException e) {
			// log.error(e);
		}
		return parmValue;
	}
	public static String decodeString(String value) {
		String parmValue = parm2String(value, "");
		try {
			parmValue = URLDecoder.decode(parmValue, "utf-8");
		} catch (UnsupportedEncodingException e) {
			// log.error(e);
		}
		return parmValue;
	}
	public static String parm2String(String value, String defaultValue) {
		return StringUtils.isNotBlank(value) ? value.trim() : defaultValue;
	}
	public static long parm2Long(String value, long defaultValue) {
		if (StringUtils.isNotBlank(value)) {
			return Long.parseLong(value);
		}
		return defaultValue;
	}
	public static Double parm2Double(String value, Double defaultValue) {
		if (StringUtils.isNotBlank(value)) {
			return Double.parseDouble(value);
		}
		return defaultValue;
	}
	public static Integer parm2Integer(String value, int defaultValue) {
		try {
			if (StringUtils.isNotBlank(value)) {
				return Integer.valueOf(value);
			} else {
				return defaultValue;
			}
		} catch (Exception e) {
			return defaultValue;
		}
	}
 
	/**
	 * 将表单数据封装成map
	 * 
	 * @param request
	 * @return
	 */
	public static Map<String, Object> convert2Map(HttpServletRequest request) {
 		Map<String, Object> map = new HashMap<String, Object>();
		@SuppressWarnings("unchecked")
		Set<Entry<String, String[]>> set = request.getParameterMap().entrySet();
		Iterator<Entry<String, String[]>> it = set.iterator();
		while (it.hasNext()) {
			Entry<String, String[]> entry = it.next();
			String key = entry.getKey();
			String[] values = entry.getValue();
			if (values.length == 1) {
				map.put(key, values[0]);
			} else if (values.length > 1) {
				map.put(key, values);
			}
		}
		return map;
	}
}